package leetcode.f1t100;

import java.util.ArrayList;
import java.util.List;

/**
 * 格式化字符串数组输出, 居中对齐, 尾行左对齐
 * https://leetcode.com/problems/text-justification/
 *
 * @Author lichongxiao
 * @Date 2022/11/23 14:34
 */
public class Q68_TextJustification {
    public List<String> fullJustify(String[] words, int maxWidth) {
        int curCount = 0, curLength = 0;
        List<String> ans = new ArrayList<>();
        for (int i = 0; i < words.length; i++) {
            int wordL = words[i].length();
            if (curLength + curCount + wordL > maxWidth) {
                if(curCount == 1){
                    ans.add(String.format("%-"+maxWidth+"s", words[i-1]));
                } else {
                    StringBuilder sb = new StringBuilder();
                    int spaceL = (maxWidth - curLength) / (curCount - 1);
                    int spaceM = (maxWidth - curLength) % (curCount - 1);
                    StringBuilder spaceB = new StringBuilder();
                    while (spaceL-- > 0) {
                        spaceB.append(" ");
                    }
                    String space = spaceB.toString();
                    while (curCount > 0) {
                        sb.append(words[i - curCount]).append(space);
                        if (spaceM-- > 0) {
                            sb.append(" ");
                        }
                        curCount--;
                    }
                    ans.add(sb.toString().trim());
                }
                curCount = 0;
                curLength = 0;
            }
            curLength += wordL;
            curCount++;
        }
        if (curCount > 0) {
            StringBuilder sb = new StringBuilder();
            while (curCount > 0) {
                sb.append(words[words.length - curCount]).append(" ");
                curCount--;
            }
            if (sb.length() > maxWidth) {
                ans.add(sb.substring(0, maxWidth));
            } else {
                ans.add(String.format("%-"+maxWidth+"s", sb.toString()));
            }
        }
        return ans;
    }

    public static void main(String[] args) {
        Q68_TextJustification bean = new Q68_TextJustification();
        List<String> strings = bean.fullJustify(new String[]{"What","must","be","acknowledgment","shall","be"}, 16);
        for (String str : strings) {
            System.out.println("_" + str + "_");
        }
    }
}
